package com.kordar.admin.enums;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class EnumUtils {

    public static <T> Map<String, String> EnumToMapString(Class<T> clzz, String... methodNames) {
        Map<String, String> enummap = new HashMap<>();
        if (!clzz.isEnum()) {
            return enummap;
        }
        // 获取所有常量
        Object[] objects = clzz.getEnumConstants();
        //获取指定方法
        Method codeMethod = null;
        Method nameMethod = null;
        try {
            codeMethod = clzz.getMethod("getCode");
            nameMethod = clzz.getMethod("getName");
            for (Object obj : objects) {
                String code = (String) codeMethod.invoke(obj);
                String name = (String) nameMethod.invoke(obj);
                enummap.put(code, name);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return enummap;
    }

    /**
     * 枚举转map结合value作为map的key,description作为map的value
     *
     * @param clzz
     * @param methodNames
     * @return enum mapcolloction
     */
    public static <T> Map<Integer, String> EnumToMapInt(Class<T> clzz, String... methodNames) {
        Map<Integer, String> enummap = new HashMap<>();
        if (!clzz.isEnum()) {
            return enummap;
        }
        // 获取所有常量
        Object[] objects = clzz.getEnumConstants();
        //获取指定方法
        Method codeMethod = null;
        Method nameMethod = null;
        try {
            codeMethod = clzz.getMethod("getCode");
            nameMethod = clzz.getMethod("getName");
            for (Object obj : objects) {

                Integer code = (Integer) codeMethod.invoke(obj);
                String name = (String) nameMethod.invoke(obj);
                enummap.put(code, name);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return enummap;
    }

    public static <T> String ValueByCode(Class<T> clzz, Object key) {
        // 获取所有常量
        Object[] objects = clzz.getEnumConstants();
        try {
            Method method = clzz.getMethod("getCode");
            Method nameMethod = clzz.getMethod("getName");
            for (Object obj : objects) {
                Object code = method.invoke(obj);
                if (code.equals(key)) {
                    return (String) nameMethod.invoke(obj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
